package es.upv.tricia.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import org.xmlpull.v1.XmlSerializer;

import es.upv.tricia.HighScore;
import es.upv.tricia.HighScoreList;

import android.content.Context;
import android.util.Log;
import android.util.Xml;

public class HighScoreReader
{
	final private static int MAX_HIGHSCORE_USERS = 25;

	private static final String SCORES_XML_FILE = "scores.xml";

	private final static String XML_SCORES_TAG = "scores";
	private final static String XML_SCORE_TAG = "score";
	private final static String XML_SCORE_USERNAME = "username";
	private final static String XML_SCORE_SCORE = "score";
	private final static String XML_SCORE_RANKING = "ranking";

	private static HighScoreList generateInitialUsers()
	{
		HighScoreList highScoreList = new HighScoreList();
		highScoreList.getScores().add(
				new HighScore("bschussek@gmail.com", "Bernhard", 1337));
		highScoreList.getScores().add(
				new HighScore("david.seide@gmail.com", "david", 1336));
		return highScoreList;
	}

	static public HighScoreList loadHighScores(Context context)
	{
		FileInputStream inputStream;
		XmlPullParser parser;
		HighScoreList highScoreList = new HighScoreList();

		try {

			inputStream = context.openFileInput(SCORES_XML_FILE);

			parser = XmlPullParserFactory.newInstance().newPullParser();
			parser.setInput(inputStream, null);

			int eventType = XmlPullParser.START_DOCUMENT;
			while (eventType != XmlPullParser.END_DOCUMENT) {
				if (eventType == XmlPullParser.START_TAG
						&& parser.getName().equals(XML_SCORE_SCORE)) {
					HighScore highScore = new HighScore();
					highScore.setUsername(parser.getAttributeValue(null,
							XML_SCORE_USERNAME));
					highScore.setScore(Integer.parseInt(parser
							.getAttributeValue(null, XML_SCORE_SCORE)));
					highScoreList.getScores().add(highScore);
				}
				eventType = parser.next();
			}
			inputStream.close();
		} catch (FileNotFoundException e) {
			return generateInitialUsers();
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return highScoreList;
	}

	static public void saveHighScores(Context context,
			HighScoreList highScoreList)
	{
		XmlSerializer serializer = Xml.newSerializer();
		StringWriter writer = new StringWriter();

		try {
			List<HighScore> highScores = highScoreList.asSortedList();

			serializer.setOutput(writer);
			serializer.startDocument(null, null);
			serializer.startTag(null, XML_SCORES_TAG);
			serializer.text(new String("\n").toCharArray(), 0, 1);

			for (int i = 0; i < MAX_HIGHSCORE_USERS && i < highScores.size(); i++) {
				HighScore highScore = highScores.get(i);

				serializer.startTag(null, XML_SCORE_TAG);
				Log.d("Scores",
						highScore.getUsername() + " " + highScore.getScore()
								+ " " + i + 1);
				serializer.attribute(null, XML_SCORE_USERNAME,
						highScore.getUsername());
				serializer.attribute(null, XML_SCORE_SCORE,
						Integer.toString(highScore.getScore()));
				serializer.attribute(null, XML_SCORE_RANKING,
						Integer.toString(i + 1));
				serializer.endTag(null, XML_SCORE_TAG);
				serializer.text(new String("\n").toCharArray(), 0, 1);
			}
			serializer.endTag(null, XML_SCORES_TAG);
			serializer.endDocument();

			FileOutputStream fos = context.openFileOutput(SCORES_XML_FILE,
					Context.MODE_PRIVATE);

			fos.write(writer.toString().getBytes());
			fos.flush();
			fos.close();
		} catch (IllegalArgumentException e1) {
			e1.printStackTrace();
		} catch (IllegalStateException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}
}
